from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, get_list_or_404
import logging
from django.core.cache import cache
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_exempt
from bulls.models import LoginForm, Banner, Article, Category

logging.basicConfig(level=logging.INFO)


def index(request):
    banners = Banner.objects.order_by('-create_time').all()[0:5:]
    news = Article.objects.order_by('-create_time').all()
    categories = process_category()

    # columns = process_category(categories)
    # categories.
    return render(request,'bulls/index.html',locals())

def detail(request,column_id):
    categories = process_category()
    return render(request,'bulls/detail.html',locals())

def content(request,news_id):
    article= get_object_or_404(Article,pk=news_id)
    categories = process_category()
    return render(request,'bulls/detail.html',locals())

def login(request):
    path = request.path
    url = request.get_full_path()
    agent = request.META['HTTP_USER_AGENT']
    form = LoginForm()

    return render(request,'bulls/login.html',locals())

def process_category():
    categories = cache.get('categories')
    logging.info(type(categories))
    if categories is None:
        logging.info('the cache of category is none')
        categories = get_list_or_404(Category,parent = None)
        for category in categories:
            category.childs = category.category_set.all()
        cache.set('categories', categories)
    else:
        logging.info('the cache of category is not none!')
    return categories

@csrf_exempt
def upload(request):
    if request.method == 'POST':
        file = request.FILES['file0']
        from PIL import Image
        image = Image.open(file)
        from datetime import datetime
        # filename = int(datetime.now().timestamp())
        filename = datetime.now().strftime('%H-%M-%S-%f')
        import os
        print(os.path.abspath('.'))
        dir_name = 'static/image/%s' % datetime.now().strftime('%Y-%m-%d')
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)
        result =  '%s/%s%s'%(dir_name,filename,os.path.splitext(file.name)[1])
        image.save(result)
        # file.save()
        return HttpResponse(result)

def get_extend(filename):
    r_index = filename.rindex('.')
    cut_len = len(filename)-r_index-1
    return filename[-cut_len:]
